package com.mawc.equipower.socket2;

import com.mawc.equipower.enums.Electric;
import com.mawc.equipower.utils.HexEcodeUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.time.LocalDateTime;


/**
 * @author zhoujian
 * 自定义封装的连接的客户端
 */
@Slf4j
@Data
public class ClientSocket implements Runnable{

    private Socket socket;
    private DataInputStream inputStream;
    private DataOutputStream outputStream;
    private String key;
    private String message;

    @Override
    public void run() {
        while (true){
            try {
                SocketHandler.onMessage(this);
                this.onMessage();
                this.handleMessage(this.message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (SocketHandler.isSocketClosed(this)){
                log.info("客户端已关闭,其Key值为：{}", this.getKey());
                //关闭对应的服务端资源
                SocketHandler.close(this);
                break;
            }
        }
    }

    /**
     * 获取指定客户端的上传信息
     * @param clientSocket
     * @return
     */
    public void onMessage(){
        byte[] keyByte = new byte[1024];
        byte[] msgByte = new byte[1];
        try {
            // 第一次先发送序列号
            if(StringUtils.isEmpty(this.getKey())) {
                this.getInputStream().read(keyByte);
                this.setKey(new String(keyByte, "UTF-8"));
                //return clientSocket.getKey();
                // 以后发送数据
            }else {
                String info = "";
                while (true) {
                    if (this.getInputStream().available() > 0) {
                        this.getInputStream().read(msgByte);
                        String tempStr = HexEcodeUtil.ByteArrayToHexStr(msgByte);
                        info += tempStr;
                        //已经读完
                        if (this.getInputStream().available() == 0) {
                            //重置,不然每次收到的数据都会累加起来
                            this.setMessage(info);
                            break;
                        }
                    }
                }
                //return clientSocket.getMessage();
            }
        } catch (IOException e) {
            e.printStackTrace();
            this.close();
        }
        //return null;
    }

    /**
     * 指定Socket资源回收
     * @param clientSocket
     */
    public void close(){
        log.info("进行资源回收");
        log.info("开始回收socket相关资源，其Key为{}", this.getKey());
        SocketPool.remove(this.getKey());
        Socket socket = this.getSocket();
        try {
            socket.shutdownInput();
            socket.shutdownOutput();
        } catch (IOException e) {
            log.error("关闭输入输出流异常，{}", e);
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                log.error("关闭socket异常{}", e);
            }
        }
    }

    public void handleMessage(String message) {
        log.info(LocalDateTime.now()+"当前设备:"+this.key+" 接收到数据: <<<<<<" + this.message);
        Electric electric = Electric.getValue(message);
        switch (electric) {
            case LOGIN:
                SocketHandler.sendMessage(this, Electric.ANSWER1.getCode());
                break;
            case DATA_BEAT:
                SocketHandler.sendMessage2(this, Electric.ANSWER2.getCode());
                break;
            case HEART_BEAT:
                SocketHandler.sendMessage3(this, Electric.ANSWER3.getCode());
        }

//        String str = this.message;
//        if (message.length() > 1000) {
//            String s1 = str.substring(0,1115);
//        if (s1 == "DATA_BEAT"){
//            Electric electric1 = Electric.getValue(message);
//            SocketHandler.sendMessage2(this, electric1.ANSWER2.getCode());
//        }
//        }

    }

}